<template>
<el-form ref="ruleFormRef" style="width: 600px;margin: auto;" :model="form" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>

  <el-form-item label="父级菜单" prop="pid">
    <el-select v-model="form.pid" placeholder="请选择父级菜单" size="large">
      <el-option label="顶级菜单" :value="0"></el-option>
      <el-option v-for="item in menuData" :key="item.menuId" :label="item.menuName" :value="item.menuId"/>
    </el-select>
  </el-form-item>

  <el-form-item label="菜单名称" prop="menuName">
    <el-input v-model="form.menuName" />
  </el-form-item>

  <el-form-item label="跳转的Url地址" prop="url">
    <el-input v-model="form.url" />
  </el-form-item>

  <el-form-item>
    <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
  </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'
import axios from 'axios';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute();
const router = useRouter();

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()


const form: any = reactive({
  pid: null,
  menuName: '',
  url:'',
})

//规则
const rules = reactive<FormRules>({
  pid: [
    { required: true, message: '请选择父级菜单', trigger: 'change',},
  ],
  menuName: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
  ],
  url: [
    { required: true, message: '请输入跳转的Url地址', trigger: 'blur' },
  ],
})

onMounted(() => {
  getMenuList()
})

const menuData:any=ref([])
//获取菜单列表
const getMenuList = () => {
  let menu = {
    userId:1
  }
  axios.post('/api/MenuManagement/SearchMenuList',menu).then(res=>{
    console.log(res);
    menuData.value=res.data.data
  }).catch(err=>{
    console.log(err);
    
  })    
}

//保存
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let menuData: any = {
        pid:form.pid,
        menuName: form.menuName,
        url:form.url
      }
      axios.post('/api/MenuManagement/CreateMenu', menuData).then(res => {
        console.log(res);
        if (res.data.code == 1) {
          ElMessage.success("保存成功!")
          router.push({
            'name':'MenuList'
          })
        }else if (res.data.code == -2) {
          ElMessage.error("该菜单名称已存在,请重新输入")
          return
        } else {
          ElMessage.error("保存失败!")
          return
        }
      }).catch(err => {
        console.log(err);

      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

</script>

<style scoped>

</style>